package com.leinao.browse.service.impl;

import com.leinao.browse.dao.BrowseRecordMapper;
import com.leinao.browse.model.BrowseRecord;
import com.leinao.browse.service.BrowseRecordService;
import com.leinao.commons.Response;
import com.leinao.constant.Constant;
import com.leinao.constant.ProjectErrorEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @Description 功能浏览记录服务
 * @author lizi
 * @date 2019/03/23 下午6:48
 * @Version 1.0
 */
@Service
public class BrowseRecordServiceImpl implements BrowseRecordService {
	
	private static Logger logger = LoggerFactory.getLogger(BrowseRecordServiceImpl.class);

    @Autowired
    private BrowseRecordMapper browseRecordMapper;

    /**
     * 功能描述：按照浏览类型和id查询浏览记录
     * @param type 功能浏览类型
     * @param userId 用户id
     * @return com.leinao.commons.Response<com.leinao.browse.model.BrowseRecord> 记录对象
     * @Author: guoliangbo
     * @Date: 2019/4/18 16:00
     */
	@Override
	public Response<BrowseRecord> getBrowseRecordByTypeAndUserId(Integer type, String userId) {
		BrowseRecord browseRecord = browseRecordMapper.getBrowseRecordByTypeAndUserId(type, userId);
		return Response.ok(browseRecord);
	}

    /**
     * 功能描述：添加用户浏览记录
     * @param type 功能浏览类型
     * @param userId 用户id
     * @return com.leinao.commons.Response<java.lang.Long> 添加影响行数
     * @Author: guoliangbo
     * @Date: 2019/4/18 16:01
     */
	@Override
	@Transactional(value ="transactionManager", propagation = Propagation.REQUIRED)
	public Response<Long> addBrowseRecord(Integer type, String userId) {
		BrowseRecord browseRecord = browseRecordMapper.getBrowseRecordByTypeAndUserId(type, userId);
		if(browseRecord != null) {
			return Response.error( Constant.RESPONSE_STATUS_SUCCESS, ProjectErrorEnum.BROWSE_RECORD_EXISTS.getSeq(), ProjectErrorEnum.BROWSE_RECORD_EXISTS.getDesc(), null);
		}

		browseRecord = new BrowseRecord();
		browseRecord.setType(type);
		browseRecord.setUserId(userId);
		long now = System.currentTimeMillis();
		browseRecord.setCreateTime(now);
		browseRecord.setUpdateTime(now);
		browseRecordMapper.insertBrowseRecord(browseRecord);
		return Response.ok(browseRecord.getId());
	}
}